package com.examination.client.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.examination.client.config.SpringConfig;
import com.examination.client.config.WechatAccountConfig;
import com.examination.client.domian.dto.PushMessageDTO;
import com.examination.client.entity.CourierInfo;
import com.examination.client.entity.CourierSite;
import com.examination.client.entity.WechatUser;
import com.examination.client.enums.CourierStatusEnum;
import com.examination.client.enums.DeleteStatusEnum;
import com.examination.client.exception.BusinessException;
import com.examination.client.mapper.WechatUserMapper;
import com.examination.client.service.ICourierInfoService;
import com.examination.client.service.ICourierSiteService;
import com.examination.client.service.IWechatUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.examination.client.util.UserInfoUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

/**
 * <p>
 * 微信用户表 服务实现类
 * </p>
 *
 * @author xiaodong
 * @since 2021-10-28
 */
@Slf4j
@Service
public class WechatUserServiceImpl extends ServiceImpl<WechatUserMapper, WechatUser> implements IWechatUserService {

    @Resource
    ICourierInfoService courierInfoService;

    @Resource
    ICourierSiteService courierSiteService;
    @Resource
    WxMpService wxMpService;

    @Autowired
    private WechatAccountConfig wechatAccountConfig;

    @Autowired
    @Qualifier(SpringConfig.ASYNC_EXECUTOR)
    Executor asyncExecutor;

    @Override
    public Boolean message() throws Exception {



        LambdaQueryWrapper<CourierInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CourierInfo::getSiteId, UserInfoUtil.getSiteId());
        queryWrapper.eq(CourierInfo::getCourierStatus, CourierStatusEnum.STORAGE.getCode());
        queryWrapper.eq(CourierInfo::getDeleteStatus, DeleteStatusEnum.NOT_DELETED.getCode());
        List<CourierInfo> courierInfoList = courierInfoService.list(queryWrapper);
        if (CollectionUtil.isEmpty(courierInfoList)) {
            return true;
        }
        CompletableFuture.runAsync(() -> {
            sendMsg(courierInfoList);
        }, asyncExecutor);
        return true;
    }

    private void sendMsg(List<CourierInfo> courierInfoList) {
        for (CourierInfo courierInfo: courierInfoList) {
            LambdaQueryWrapper<CourierSite> siteQueryWrapper = new LambdaQueryWrapper<>();
            siteQueryWrapper.eq(CourierSite::getId, courierInfo.getSiteId());
            CourierSite courierSite = courierSiteService.getOne(siteQueryWrapper);

            if (Objects.isNull(courierSite)) {
                throw new RuntimeException("站点不存在");
            }

            LambdaQueryWrapper<WechatUser> wechatUserQueryWrapper = new LambdaQueryWrapper<>();
            wechatUserQueryWrapper.like(WechatUser::getUserPhone,courierInfo.getUserPhone());
            WechatUser wechatUser = getOne(wechatUserQueryWrapper);
            if (Objects.nonNull(wechatUser)) {
                sendMsg(wechatUser.getOpenId(),courierSite.getSiteName(),courierSite.getPhone(),courierInfo.getCourierName(),courierInfo.getCourierCode());
            }
        }
    }


    /**
     * 发送微信模板信息
     *
     * @param openId 接受者openId
     * @return 是否推送成功
     */
    public Boolean sendMsg(String openId,String siteName,String phone,String courierName,String courierCode) {

        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser(openId)
                .templateId(wechatAccountConfig.getTemplateId())
                .url("http://www.baidu.com")
                .build();

        templateMessage.addData(new WxMpTemplateData("first", "您的快递已存入"+siteName, "#FF00FF"))
                .addData(new WxMpTemplateData("keyword1", "", "#000000"))
                .addData(new WxMpTemplateData("keyword2", courierCode, "#000000"))
                .addData(new WxMpTemplateData("keyword3", courierName, "#000000"))
                .addData(new WxMpTemplateData("keyword4", phone, "#000000"))
                .addData(new WxMpTemplateData("remark", "请您及时取件,谢谢", "#000000"));
        String msgId = null;
        try {
            //发送模板消息
            msgId = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (WxErrorException e) {
            log.info("消息推送失败:{}", e);
            throw new RuntimeException(e.getMessage());
        }
        return StringUtils.isNotBlank(msgId);
    }
}
